<!-- 主从表容器 -->
<div class="master-detail-container">
    <!-- 主表容器 -->
    <div class="table-container" id="masterTableContainer">
        <div class="layui-card">
            <div class="layui-card-header">项目预结算差异</div>
            <div class="layui-card-body">
                <div class="table-wrapper">
                    <table id="mainTable" class="layui-table" lay-filter="mainTable">
                        <colgroup>
                            <col width="60">
                            <col width="200">
                            <col width="400">
                            <col width="80">
                            <col width="80">
                            <col width="100">
                            <col>
                        </colgroup>
                        <thead>
                            <tr>
                                <th lay-data="{'type':'numbers'}">序号</th>
                                <th lay-data="{field:'design_code'}">设计编码</th>
                                <th lay-data="{field:'project_name'}">项目名称</th>
                                <th lay-data="{field:'budget_total'}">预算金额</th>
                                <th lay-data="{field:'accept_total'}">验收金额</th>
                                <th lay-data="{field:'diff_total'}">金额差异</th>
                                <th lay-data="{field:'diff_rate'}">差异率</th>
                            </tr>
                        </thead>
                        <tbody id="mainTableBody"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>

    <div class="resize-handle" id="resizeHandle"></div>

    <div class="table-container" id="detailTableContainer">
        <div class="layui-card">
            <div class="layui-card-header">差异明细</div>
            <div class="layui-card-body">
                <div class="table-wrapper">
                    <table id="detailTable" class="layui-table" lay-filter="detailTable">
                        <colgroup>
                            <col width="60">
                            <col width="80">
                            <col width="400">
                            <col width="100">
                            <col width="100">
                            <col width="100">
                            <col width="100">
                            <col width="100">
                            <col>
                        </colgroup>
                        <thead>
                            <tr>
                                <th lay-data="{'type':'numbers'}">序号</th>
                                <th lay-data="{field:'item_code'}">条目编码</th>
                                <th lay-data="{field:'item_name'}">条目名称</th>
                                <th lay-data="{field:'item_type'}">条目类型</th>
                                <th lay-data="{field:'budget_count'}">预算数量</th>
                                <th lay-data="{field:'accept_count'}">验收数量</th>
                                <th lay-data="{field:'diff'}">差异</th>
                                <th lay-data="{field:'diff_status'}">差异状态</th>
                                <th lay-data="{field:'remark'}">备注</th>
                            </tr>
                        </thead>
                        <tbody id="detailTableBody"></tbody>
                    </table>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    (function () {
        var table = layui.table;
        var $ = layui.$;
        var layer = layui.layer;

        var currentProjectCode = '';

        function initResizeHandle() {
            const container = $('.master-detail-container');
            const master = $('#masterTableContainer');
            const handle = $('#resizeHandle');
            const detail = $('#detailTableContainer');

            let isDragging = false;

            handle.on('mousedown', function (e) {
                isDragging = true;
                $('body').css('cursor', 'row-resize');
                e.preventDefault();
            });

            $(document)
                .on('mousemove', function (e) {
                    if (!isDragging) return;

                    const containerHeight = container.height();
                    const containerOffset = container.offset().top;
                    const mouseY = e.pageY - containerOffset;
                    const newMasterHeight = Math.min(Math.max(mouseY, 100), containerHeight - 100);

                    master.css('height', newMasterHeight + 'px');
                    detail.css('height', (containerHeight - newMasterHeight - 5) + 'px');

                    $('.table-wrapper').trigger('resize');
                })
                .on('mouseup', function () {
                    isDragging = false;
                    $('body').css('cursor', '');
                });

            const containerHeight = container.height();
            master.css('height', (containerHeight * 0.5) + 'px');
            detail.css('height', (containerHeight * 0.5 - 5) + 'px');
        }

        window.initSubPage = function () {
            initResizeHandle();
            loadMainTableData();

            $("#mainTableBody").on('click', 'tr', function () {
                var projectCode = $(this).data('project-code');
                if (projectCode && projectCode !== currentProjectCode) {
                    currentProjectCode = projectCode;
                    $(this).addClass('layui-table-click').siblings().removeClass('layui-table-click');
                    loadDetailTableData(projectCode);
                }
            });

            $(window).on('resize', function () {
                const container = $('.master-detail-container');
                const master = $('#masterTableContainer');
                const detail = $('#detailTableContainer');

                const containerHeight = container.height();
                const masterHeight = master.height();

                // 保持当前比例
                const ratio = masterHeight / (masterHeight + detail.height());
                master.css('height', (containerHeight * ratio) + 'px');
                detail.css('height', (containerHeight * (1 - ratio) - 5) + 'px');
            });
        };

        function loadMainTableData() {
            var loading = layer.load(1);

            http.get(API_CONFIG.ENDPOINTS.PROJECT_DIFF)
                .then(function (res) {
                    layer.close(loading);
                    if (res.code === 0) {
                        if (res.data && res.data.length > 0) {
                            renderMainTable(res.data);
                            currentProjectCode = res.data[0].design_code;
                            $("#mainTableBody tr:first").addClass('layui-table-click');
                            loadDetailTableData(currentProjectCode);
                        } else {
                            $('#mainTableBody').empty().append('<tr><td colspan="6" class="empty-data">暂无数据</td></tr>');
                            $('#detailTableBody').empty().append('<tr><td colspan="9" class="empty-data">请先选择项目</td></tr>');
                        }
                    } else {
                        layer.msg(res.msg || '加载主表数据失败', { icon: 2 });
                    }
                })
                .catch(function (err) {
                    layer.close(loading);
                    layer.msg(err.message || '请求主表数据失败', { icon: 2 });
                    console.error('API请求失败:', err);
                });
        }

        function loadDetailTableData(projectCode) {
            var loading = layer.load(1);

            http.get(API_CONFIG.ENDPOINTS.PROJECT_DIFF_DETAIL, { project_code: projectCode })
                .then(function (res) {
                    layer.close(loading);
                    if (res.code === 0) {
                        if (res.data && res.data.length > 0) {
                            renderDetailTable(res.data);
                        } else {
                            $('#detailTableBody').empty().append('<tr><td colspan="9" class="empty-data">暂无明细数据</td></tr>');
                        }
                    } else {
                        layer.msg(res.msg || '加载明细数据失败', { icon: 2 });
                        $('#detailTableBody').empty().append('<tr><td colspan="9" class="error-data">数据加载失败</td></tr>');
                    }
                })
                .catch(function (err) {
                    layer.close(loading);
                    layer.msg(err.message || '请求明细数据失败', { icon: 2 });
                    $('#detailTableBody').empty().append('<tr><td colspan="9" class="error-data">请求失败: ' + err.message + '</td></tr>');
                    console.error('API请求失败:', err);
                });
        }

        function renderMainTable(data) {
            var $tbody = $('#mainTableBody').empty();

            data.forEach(function (item) {
                var row = $('<tr data-project-code="' + item.design_code + '"></tr>');
                row.append('<td>' + getRowNumber(data.indexOf(item)) + '</td>')
                row.append('<td>' + (item.design_code || '') + '</td>');
                row.append('<td>' + (item.project_name || '') + '</td>');
                row.append('<td style="text-align: right;">' + (item.budget_total?.toFixed(2) || '0.00') + '</td>');
                row.append('<td style="text-align: right;">' + (item.accept_total?.toFixed(2) || '0.00') + '</td>');
                row.append('<td style="text-align: right;">' + (item.diff_total?.toFixed(2) || '0.00') + '</td>');
                row.append('<td style="text-align: right;">' + (item.diff_rate?.toFixed(2) + '%' || '0.00%') + '</td>');
                $tbody.append(row);
            });
        }

        function renderDetailTable(data) {
            var $tbody = $('#detailTableBody').empty();

            data.forEach(function (item) {
                var rowClass = getDiffRowClass(item.diff_status);
                var row = $('<tr class="' + rowClass + '"></tr>');
                row.append('<td>' + getRowNumber(data.indexOf(item)) + '</td>')
                row.append('<td>' + (item.code || '') + '</td>');
                row.append('<td>' + (item.name || '') + '</td>');
                row.append('<td class="text-center">' + getItemTypeName(item.item_type) + '</td>');
                row.append('<td style="text-align: right;">' + (item.budget_count?.toFixed(2) || '0.00') + '</td>');
                row.append('<td style="text-align: right;">' + (item.accept_count?.toFixed(2) || '0.00') + '</td>');
                row.append('<td style="text-align: right;">' + (item.diff?.toFixed(2) || '0.00') + '</td>');
                row.append('<td>' + (item.diff_status || '') + '</td>');
                row.append('<td>' + (item.remark || '') + '</td>');
                $tbody.append(row);
            });
        }

        function getRowNumber(index) {
            return index + 1; // 行号从1开始
        }

        function getDiffRowClass(status) {
            if (!status) return '';

            var lowerStatus = String(status).toLowerCase().trim();

            if (['超支', 'overspend'].includes(lowerStatus)) return 'diff-row-overspend';

            if (['结余', 'saved'].includes(lowerStatus)) return 'diff-row-saved';

            return ''; // 其他状态不加样式
        }

        function getItemTypeName(type) {
            type = String(type || '');

            var typeMap = {
                '1': '材料',
                '2': '人工',
                '3': '其它'
            };

            return typeMap[type];
        }

        function getStatusColor(status) {
            var colors = {
                '超支': '#FF5722',
                '结余': '#038148',
                '相同': '#999'
            };
            return colors[status] || '';
        }
    })();
</script>

<style>
    /* 表格样式调整 */
    .layui-table {
        width: 100%;
        margin-bottom: 0;
    }

    /* 表头居中 */
    .layui-table thead th {
        text-align: center !important;
    }

    .layui-table th,
    .layui-table td {
        border-color: green !important;
        /* 同时设置表头和单元格的边框颜色 */
    }

    /* 行背景色样式 */
    .diff-row-overspend {
        background-color: #FFF2F0 !important;
        /* 浅红色背景 */
    }

    .diff-row-overspend:hover {
        background-color: #FFE6E0 !important;
        /* 悬停时稍深的红色 */
    }

    .diff-row-saved {
        background-color: #F0F9FF !important;
        /* 浅蓝色背景 */
    }

    .diff-row-saved:hover {
        background-color: #E0F2FF !important;
        /* 悬停时稍深的蓝色 */
    }

    /* 主从表容器样式 */
    .master-detail-container {
        display: flex;
        flex-direction: column;
        height: 100%;
        position: relative;
    }

    /* 表格容器样式 */
    .table-container {
        overflow: hidden;
        position: relative;
    }

    /* 可调节分隔条样式 */
    .resize-handle {
        height: 5px;
        background-color: #e6e6e6;
        cursor: row-resize;
        position: relative;
        z-index: 10;
    }

    .resize-handle:hover {
        background-color: #d2d2d2;
    }

    /* 表格包装器，用于实现滚动条 */
    .table-wrapper {
        overflow: auto;
        height: calc(100% - 50px);
        /* 减去表头高度 */
    }

    /* 卡片样式调整 */
    .layui-card {
        height: 100%;
        margin-bottom: 0;
        display: flex;
        flex-direction: column;
    }

    .layui-card-body {
        flex: 1;
        overflow: hidden;
        padding: 0;
    }


    /* 行高亮样式 */
    .layui-table-click {
        background-color: #f2f2f2 !important;
    }

    /* 空数据提示样式 */
    .empty-data {
        text-align: center;
        color: #999;
        padding: 20px !important;
    }

    .error-data {
        text-align: center;
        color: #FF5722;
        padding: 20px !important;
    }

    /* 表头固定 */
    .layui-table thead {
        position: sticky;
        top: 0;
        z-index: 9;
        background-color: #f8f8f8;
    }
</style>